package cn.broadsense.web.controller;

import cn.broadsense.biz.bo.DataItemChannelQueryBo;
import cn.broadsense.biz.bo.DataItemQueryBo;
import cn.broadsense.biz.domain.AppOperLog;
import cn.broadsense.biz.domain.DataItem;
import cn.broadsense.biz.domain.DataItemChannel;
import cn.broadsense.biz.domain.ItemTag;
import cn.broadsense.biz.dto.DataItemDto;
import cn.broadsense.biz.dto.ItemTagTemplateDto;
import cn.broadsense.biz.enums.FillTagEnum;
import cn.broadsense.biz.service.DataItemChannelService;
import cn.broadsense.biz.service.DataItemService;
import cn.broadsense.common.core.controller.BaseController;
import cn.broadsense.common.core.domain.R;
import cn.broadsense.common.core.page.TableDataInfo;
import cn.broadsense.common.core.page.TableDataInfoResult;
import cn.broadsense.common.core.text.Convert;
import cn.broadsense.common.utils.DateUtils;
import cn.broadsense.common.utils.PageUtils;
import cn.broadsense.common.utils.SecurityUtils;
import cn.broadsense.common.utils.ip.AddressUtils;
import cn.broadsense.common.utils.ip.IpUtils;
import cn.broadsense.framework.manager.AsyncManager;
import cn.broadsense.web.controller.body.DataItemCollectDataBody;
import cn.broadsense.web.controller.query.DataItemQuery;
import cn.broadsense.web.factory.AppAsyncFactory;
import com.alibaba.fastjson2.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author huangjinshi
 * @description
 * @createDate 2024-09-19 11:37:29
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/data")
@Api(tags = "信息采集模块")
public class DataItemController extends BaseController {

    private final DataItemService dataItemService;

    @Autowired
    private DataItemChannelService dataItemChannelService;

    @Autowired
    public DataItemController(DataItemService dataItemService) {
        this.dataItemService = dataItemService;
    }

    @ApiOperation("获取列表")
    @GetMapping("/list")
    public TableDataInfo getList(DataItemQuery query) {
        PageUtils.startPage(false);
        List<DataItem> list = dataItemService.findList(DataItemQueryBo.builder().name(query.getName()).statusList(query.getStatusList()).startTime(query.getStartTime()).endTime(query.getEndTime()).collectUserId(SecurityUtils.getUserId()).build());
        return getDataTable(list);
    }

    @ApiOperation("获取详情")
    @GetMapping("/{id}")
    public R<DataItemDto> getInfo(@PathVariable Long id) {
        DataItemDto dataItemDto = dataItemService.getDtoById(id);
        if (dataItemDto == null) {
            return R.fail("当前事项不存在，请重新选择");
        }
        if (!SecurityUtils.getUserId().equals(dataItemDto.getCollectUserId())) {
            return R.fail("当前事项不属于您，请重新选择");
        }
        return R.ok(dataItemDto);
    }

    @PutMapping("/{id}/upload")
    @ApiOperation("上传数据")
    public R upload(@PathVariable Long id, @Validated @RequestBody DataItemCollectDataBody body) throws IllegalAccessException {
        DataItemDto dataItemDto = dataItemService.getDtoById(id);
        if (dataItemDto == null) {
            return R.fail("当前事项不存在，请重新选择");
        }
        if (!SecurityUtils.getUserId().equals(dataItemDto.getCollectUserId())) {
            return R.fail("当前事项不属于您，请重新选择");
        }
        if (dataItemDto.getStatus() != null && dataItemDto.getStatus().equals(3)) {
            return R.fail("当前事项已完成，请勿反复提交");
        }
        ItemTagTemplateDto itemTagTemplate = dataItemDto.getItemTagTemplate();
        Map<String, Object> map = Convert.convertToMap(body);
        if (itemTagTemplate != null) {
            List<ItemTag> itemTagList = itemTagTemplate.getItemTagList();
            for (ItemTag itemTag : itemTagList) {
                if (itemTag.getIsRequired() != null && itemTag.getIsRequired().equals(1)) {
                    if (Objects.isNull(map.get(itemTag.getFieldNameDb()))) {
                        return R.fail(FillTagEnum.getFiledName(itemTag.getFieldNameDb()) + "为必填项");
                    }
                }
            }
            dataItemDto.setCollectData(JSONObject.toJSONString(body));
            dataItemDto.setHoldTime(null);
            dataItemDto.setHoldCollectData(null);
            dataItemDto.setSubmitTime(DateUtils.getNowDate());
            dataItemDto.setStatus(1);
            dataItemService.updateById(dataItemDto);
            AsyncManager.me().execute(AppAsyncFactory.recordAppOperLog(AppOperLog.builder()
                    .title("标签信息")
                    .businessType(2)
                    .userId(SecurityUtils.getUserId())
                    .operIp(IpUtils.getIpAddr())
                    .operLocation(AddressUtils.getRealAddressByIP(IpUtils.getIpAddr()))
                    .relationModule(2)
                    .relationId(dataItemDto.getId())
                    .relationContent(JSONObject.toJSONString(dataItemDto))
                    .operTime(DateUtils.getNowDate())
                    .build()));
            return R.ok();
        } else {
            return R.fail("当前事项还未选择信息采集模板，请联系管理员处理");
        }

    }

    @PutMapping("/{id}/tempUpload")
    @ApiOperation("暂存数据")
    public R tempUpload(@PathVariable Long id, @RequestBody DataItemCollectDataBody body) throws IllegalAccessException {
        DataItemDto dataItemDto = dataItemService.getDtoById(id);
        if (dataItemDto == null) {
            return R.fail("当前事项不存在，请重新选择");
        }
        if (!SecurityUtils.getUserId().equals(dataItemDto.getCollectUserId())) {
            return R.fail("当前事项不属于您，请重新选择");
        }
        if (dataItemDto.getStatus() != null && dataItemDto.getStatus().equals(3)) {
            return R.fail("当前事项已完成，请勿反复提交");
        }
        ItemTagTemplateDto itemTagTemplate = dataItemDto.getItemTagTemplate();
        if (itemTagTemplate != null) {
            dataItemDto.setHoldCollectData(JSONObject.toJSONString(body));
            dataItemDto.setHoldTime(DateUtils.getNowDate());
            dataItemDto.setStatus(0);
            dataItemService.updateById(dataItemDto);
            AsyncManager.me().execute(AppAsyncFactory.recordAppOperLog(AppOperLog.builder()
                    .title("草稿数据")
                    .businessType(3)
                    .userId(SecurityUtils.getUserId())
                    .operIp(IpUtils.getIpAddr())
                    .operLocation(AddressUtils.getRealAddressByIP(IpUtils.getIpAddr()))
                    .relationModule(2)
                    .relationId(dataItemDto.getId())
                    .relationContent(JSONObject.toJSONString(dataItemDto))
                    .operTime(DateUtils.getNowDate())
                    .build()));
            return R.ok();
        } else {
            return R.fail("当前事项还未选择信息采集模板，请联系管理员处理");
        }
    }


    @ApiOperation(value = "获取数据接入点位列表")
    @GetMapping("/channelList")
    public TableDataInfoResult<List<DataItemChannel>> channelList(DataItemChannelQueryBo queryBo) {
        List<DataItemChannel> dataItemChannelList = dataItemChannelService.findList(queryBo);
        return getDataTableResult(dataItemChannelList);
    }


}
